<template>
  <div class="article" v-if="articles.length>0">
    <el-col class="left">
      <el-menu :default-active="openeds+'-0'" class="el-menu-vertical-demo" @open="handleOpen" @close="handleClose"
               background-color="#D9DEE4" :default-openeds="openeds"
               text-color="#000">
        <div class="selectName"></div>
        <el-submenu v-for="(item,index) in category" v-if='item.children.length>0' :key="index" :index="''+index">
          <template slot="title">
            <span>{{item.name}}</span>
          </template>
          <el-menu-item v-if="item.children.length>0" v-for="(subItem,subIndex) in item.children" :key="index"
                        :index="index+'-'+subIndex" @click="setId(subItem.id)">{{subItem.name}}
          </el-menu-item>
        </el-submenu>
      </el-menu>
    </el-col>
    <div class="right">
      <router-link :to="{ name: 'addArticle'}">
        <el-button type="primary" icon="el-icon-plus">新增</el-button>
      </router-link>
      <div class="table-toolbar">
        <el-select v-model="status" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-date-picker
          v-model="datetime"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions2">
        </el-date-picker>
        <el-input
          placeholder="请输入内容"
          prefix-icon="el-icon-search"
          v-model="search"
          style="width:200px;">
        </el-input>
        <el-button type="primary" @click="getArticles">查询</el-button>
        <el-button type="info" @click="clearSearchInfo">清空</el-button>
      </div>
      <el-table
        :data="this.articles"
        stripe
        @sort-change="sortChange"
        @row-contextmenu="rowContextClick"
        style="width: 100%">
        <el-table-column
          label="序号"
          type="index"
          width="100">
        </el-table-column>
        <el-table-column
          prop="state"
          label="状态"
          width="180">
          <template slot-scope="scope">
            <span style="">{{ scope.row.state==='published'?'已发布':(scope.row.state==='draft'?'草稿':'已撤回') }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="title"
          label="标题"
          width="400">
        </el-table-column>
        <el-table-column
          prop="readTimes"
          label="阅读次数"
          sortable="custom">
        </el-table-column>
        <el-table-column
          prop="publishInfo.time"
          label="发布时间"
          sortable="custom"
          width="240"
        >
        </el-table-column>
        <el-table-column
          prop="lastModifyInfo.time"
          label="修改时间"
          sortable="custom"
          width="240"
        >
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="200">
          <template slot-scope="scope">
            <router-link :to="{ name: 'editArticle',query: {id:scope.row.id}}" v-if="!showOpt(scope.row.state)">
              <el-button @click="" type="text" size="small">编辑</el-button>
            </router-link>
            <el-button type="text" size="small" @click="editArticleById(scope.row.id)"
                       v-if="!showOpt(scope.row.state)">删除
            </el-button>
            <el-button @click="" type="text" size="small" @click="publishArticleById(scope.row.id)"
                       v-if="!showOpt(scope.row.state)">发布
            </el-button>
            <el-button type="text" size="small" @click="withdrawArticleById(scope.row.id)"
                       v-if="showOpt(scope.row.state)">撤回
            </el-button>
            <el-button @click="" type="text" size="small" @click="topArticleById(scope.row.id)"
                       v-if="showOpt(scope.row.state)">置顶
            </el-button>
            <el-button type="text" size="small" @click="untopArticleById(scope.row.id)" v-if="showOpt(scope.row.state)">
              取消置顶
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block" style="margin-top: 30px;text-align: right;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
      <div class="modal" v-show="modal.visible"
           :style="{left:modal.left+'px',top:modal.top+'px'}"
           @mouseleave="hideModal">
        <div v-for="(item,index) in navList" :key="index" :index="''+index" @click="deleteArticleById">
          <i :class="item.icon"></i>
          <span class="optName">{{item.name}}</span>
        </div>
      </div>
    </div>

    <el-dialog
      title="撤销"
      :visible.sync="dialogVisible"
      width="30%">
      <el-input
        placeholder="请输入撤销原因"
        type="textarea"
        v-model="withDrawReason"
        style="width:100%;">
      </el-input>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="withdraw()">确 定</el-button>
  </span>
    </el-dialog>
  </div>
  <div v-else> 暂无数据</div>
</template>

<script>
  import { mapGetters, mapActions } from 'vuex'
  import myTable from './Table.vue'

  export default {
    name: 'College',
    data () {
      return {
        withDrawReason: '',//撤回理由
        dialogVisible: false,//弹出框显示隐藏
        articleId: 0,
        modal: {
          visible: false,
          left: 0,
          top: 0
        },
        options: [{
          value: '0',
          label: '全部'
        }, {
          value: 'draft',
          label: '草稿'
        }, {
          value: 'published',
          label: '已发布'
        }, {
          value: 'withdrawn',
          label: '已撤回'
        }],
        status: '0',
        articles: [],
        currentPage: 1,
        pageSize: 20,
        sorts: {
          field: 'lastModifiedTime',
          order: -1
        },
        total: 0,
        pickerOptions2: {
          shortcuts: [{
            text: '最近一周',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一个月',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近三个月',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '清空',
            onClick (picker) {
              picker.$emit('pick', ['', ''])
            }
          }]
        },
        datetime: '',
        search: '',
        openeds: [],
      }
    },
    mounted () {
      this.getJson()
    },
    components: {
      myTable: myTable
    },
    computed: {
      ...mapGetters([
        'category', //左边菜单
        'categoryID',//菜单id
        'searchValue',//查询关键字
        'type',//主菜单
        'navList'
      ])
    },
    methods: {
      ...mapActions([
        'setCategory',
        'setType',
        'setCategoryID'
      ]),
      //获取子菜单
      async getJson () {
        if (this.type === '') {
          this.setType({
            enName: this.navList[0].enName,
            name: this.navList[0].name
          })
        }
        let res = await this.axios.get(`/api/admin/dictionary/college/all`)
        if (res.data.state === 0) {
          if (res.data.bizData.length > 0) {
            this.setCategory(res.data.bizData)
            let i, j
            for (i = 0; j = this.category.length, i < j; i++) {
              if (this.category[i].children.length > 0) {
                this.openeds.push(String(i))
                this.setCategoryID(this.category[i].children[0].id)
                this.getArticles()
                return
              }
            }
          }
        }
      },
      //获取文章列表
      async getArticles () {
        let res = await this.axios.post('/api/admin/article/query', {
          category: this.categoryID,
          publishStartDate: this.datetime[0],
          publishEndDate: this.datetime[1],
          pagingParam: {
            pageNumber: this.currentPage,
            pageSize: this.pageSize,
            sorts: [
              this.sorts
            ]
          },
          search: this.search,
          type: 'college',
          state: this.status === '0' ? null : this.status
        })
        if (res.data.state === 0) {
          this.articles = res.data.bizData.items
          this.total = res.data.bizData.totalItemCount
//          this.total =
        }
      },
      setId (id) {
        this.setCategoryID(id)
        this.getArticles()
      },
      handleOpen (key, keyPath) {
        console.log(key, keyPath)
      },
      handleClose (key, keyPath) {
        console.log(key, keyPath)
      },
      handleSizeChange (val) {
        this.pageSize = val
      },
      handleCurrentChange (val) {
        this.currentPage = val
      },
      sortChange (column) {
        this.sorts = {
          field: column.prop,
          order: column.order === 'ascending' ? -1 : 0
        }
        this.getArticles()
      },
      clearSearchInfo () { //清空过滤条件
        this.search = ''
        this.status = '0'
        this.datetime = ['', '']
      },
      rowContextClick (row, event) {
        console.log(row)
        this.articleId = row.id
        this.modal.visible = true
        let winWidth = document.body.clientWidth
        let clientLeft = event.clientX
        if (winWidth - clientLeft < 60) {
          clientLeft -= 60
        }
        this.modal.left = clientLeft
        this.modal.top = event.clientY
        if (event.button === 2) {
          event.preventDefault()
        }
      },
      hideModal () {
        this.modal.visible = false
      },
      deleteArticleById (id = this.articleId) { //删除文章nag
        this.$confirm('您确定要删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let res = await this.axios.post(`/api/admin/article/${id}/remove`)
          if (res.data.state === 0) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getArticles()
          } else {
            this.$message.error(res.data.errorMessage)
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      },
      publishArticleById (id = this.articleId) { //发布文章nag
        this.$confirm('您确定要发布吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let res = await this.axios.post(`/api/admin/article/${id}/publish`)
          if (res.data.state === 0) {
            this.$message({
              type: 'success',
              message: '发布成功!'
            })
            this.getArticles()
          } else {
            this.$message.error(res.data.errorMessage)
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      },
      topArticleById (id = this.articleId) { //置顶文章
        this.$confirm('您确定要置顶吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let res = await this.axios.post(`/api/admin/article/${id}/top`)
          if (res.data.state === 0) {
            this.$message({
              type: 'success',
              message: '置顶成功!'
            })
            this.getArticles()
          } else {
            this.$message.error(res.data.errorMessage)
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      },
      untopArticleById (id = this.articleId) { //取消删除文章
        this.$confirm('您确定要取消置顶吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let res = await this.axios.post(`/api/admin/article/${id}/untop`)
          if (res.data.state === 0) {
            this.$message({
              type: 'success',
              message: '取消成功!'
            })
            this.getArticles()
          } else {
            this.$message.error(res.data.errorMessage)
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      },
      withdrawArticleById (id) { //撤销文章
        this.articleId = id
        this.dialogVisible = true
      },
      async withdraw (id = this.articleId) {
        if (this.withDrawReason === '') {
          this.$message.error('必须填写撤销理由!')
          return false
        }
        let res = await this.axios.post(`/api/admin/article/${id}/withdraw?note=${this.withDrawReason}`)
        if (res.data.state === 0) {
          this.$message({
            type: 'success',
            message: '撤销成功!'
          })
          this.dialogVisible = false
          this.getArticles()
        } else {
          this.$message.error(res.data.errorMessage)
        }
      },
      clickfn (fn) { //强转为方法
        Function(fn())
      },
      showOpt (state) { //操作按钮过滤
        return state === 'published' ? true : false
      },
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="stylus" type="text/stylus">
  .article
    display flex
    width 100%
    height 100%
    background #fff
    .left
      width 300px
      .selectName
        height 40px
        width 100%
        text-align center
        line-height 40px
    .right
      flex 1
      padding 15px
      overflow-y auto

  .el-pagination button, .el-pagination span:not([class*=suffix])
    font-size 16px

  .el-table
    font-size 16px

  .el-menu
    border-right none
    height 100%

  .el-menu-item.is-active
    background-color #fff

  .table-toolbar
    padding 10px 0
    text-align right
    > *
      margin-left 30px

  .modal
    position fixed
    padding 15px 0
    height auto
    background #fff
    font-size 14px
    > div
      height 30px
      line-height 30px
      padding 0 15px
      cursor pointer
      &:hover
        background #93c6ef
      .optName
        padding-left 15px


</style>
